package ccm.component.image;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class ResizeableImageJPanel extends ImageJPanel
{
    /**
     * 用于保存缩放的比例
     */
    protected float resizeRate;

    public ResizeableImageJPanel()
    {
        this(null);
    }


    public ResizeableImageJPanel(BufferedImage image)
    {
        super(image);
        resizeRate=1;
        updateImg();
    }

    /**
     * 更新图片并处理缩放
     */
    protected void updateImg()
    {
        if(image==null||resizeRate<=0)
        {return;}
        int w=(int)(image.getWidth()*resizeRate);
        int h=(int)(image.getHeight()*resizeRate);
        imgJLabel.setIcon(new ImageIcon(image.getScaledInstance(w,h,Image.SCALE_SMOOTH)));
    }

    /**
     * 鼠标点击时处理缩放关系并向上触发点击事件
     */
    public void mouseClicked(MouseEvent e)
    {
        if(e.getSource().equals(imgJLabel))
        {
            imageJPanelListener.forEach(l->l.imageClicked(new ImageEvent(this,1,"clicked",(int)(e.getX()/resizeRate),(int)(e.getY()/resizeRate))));
        }
    }

    /**
     * 获取当前缩放的比例
     *
     * @return 缩放的比例
     */
    public double getResizeRate()
    {
        return resizeRate;
    }

    /**
     * 设置缩放的比例
     *
     * @param resizeRate 缩放的比例
     */
    public void setResizeRate(float resizeRate)
    {
        this.resizeRate=resizeRate;
        updateImg();
    }
}
